package com.smforj.ssm.modules.wc.util;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.smforj.ssm.wechat.util.CookieUtil;
import com.smforj.ssm.wechat.util.JsSignUtil;
 
 

public class JsapiUtil {

	/***
	 * 设置jsapi tocket
	 * @param request
	 * @param response
	 * @param openid
	 * @param map
	 * @date 2016-8-22 下午2:05:16
	 */
	public static void setJsapiTicket(HttpServletRequest request,HttpServletResponse response
			,String openid,Map<String,Object> map)
	{
		String url = request.getRequestURL().toString().trim();
		//去除url中后的jsessionid
		int index = url.indexOf(";jsessionid");
		if(index > -1)
			url = url.substring(0, index);
		String cname = (url+openid).trim();  
		Cookie cookie = CookieUtil.getCookieByName(request, cname);
		JSONObject json = null;
		if(cookie == null)
		{
			Map<String,String> smap = JsSignUtil.sign(url); 
			json = JSONObject.fromObject(smap); 
			CookieUtil.addCookie(response, cname, json.toString(), 6000);
		}else
			json = JSONObject.fromObject(cookie.getValue()); 
		
		map.put("url", json.get("url"));
		map.put("jsapi_ticket", json.get("jsapi_ticket"));
		map.put("nonceStr", json.get("nonceStr"));
		map.put("timestamp", json.get("timestamp"));
		map.put("signature", json.get("signature"));
		map.put("appId", json.get("appId"));
		
		System.out.println("setTicketParam map: "+map);
	}
}
